package com.dlc.yunguang.activitynew;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.widget.TitleBar;
import com.dlc.yunguang.activity.OrderDetailActivity1;
import com.dlc.yunguang.adapter.DistributeAdapter;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.net.bean.BackBean;
import com.dlc.yunguang.net.bean.OrderDetailBean;
import com.dlc.yunguang.net.bean.OrderRfidsBean;
import com.dlc.yunguang.net.bean.RFIDListBean;
import com.dlc.yunguang.net.bean.RFIDSpecListBean;
import com.dlc.yunguang.net.bean.StockCheckData;
import com.dlc.yunguang.net.exception.ErrorMsgException;
import com.dlc.yunguang.net.protocol.StockProto;
import com.dlc.yunguang.net.protocol.base.HttpProtocol;
import com.dlc.yunguang.R;
import com.trello.rxlifecycle.android.ActivityEvent;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017-07-26.
 */

public class DistributeResultActivity extends BaseActivity {
    @BindView(R.id.titleBar)
    TitleBar titleBar;
    @BindView(R.id.btn_sure)
    Button btn_sure;
    @BindView(R.id.mRecyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.order_num)
    TextView orderNum;
    @BindView(R.id.real_num)
    TextView realNum;
    @BindView(R.id.reduce_num)
    TextView reduceNum;
    @BindView(R.id.add_num)
    TextView addNum;
    //private BucaoResultAdapter mBucaoResultAdapter;
    private DistributeAdapter mDistributeAdapter;

    private String orderno;
    private String rfid = "";
    private String id = "",offic_id = "";

    private ArrayList<String> RfList = new ArrayList<>();//手持机读取的所有rfid
    private ArrayList<String> dataList = new ArrayList<>();//扫描订单二维码获取到的所有rfid

    List<RFIDListBean.DataBean.ListBean> list = new ArrayList<>();

    private List<StockCheckData> mStockCheckList = new ArrayList<>();
    private int exisNumber = 0;//存在仓库的数据
    private int NoEnvironment = 0;//非环境中的rfid

    @Override
    protected int getLayoutID() {
        return R.layout.activity_bucao_result;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        titleBar.leftImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.titleText.setText("科室分发");
        btn_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (exisNumber != NoEnvironment){
                    SureDialog sureDialog =
                        new SureDialog(DistributeResultActivity.this, getString(R.string.submit_bucao));
                    sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                        @Override
                        public void sure(){

                            if (!TextUtils.isEmpty(orderno)) {
                                rfid_divide_new(rfid,id,"");
                            }

                        }

                        @Override
                        public void cancle() {

                        }
                    });
                }else {
                  if (!TextUtils.isEmpty(orderno)) {
                      rfid_divide_new(rfid,id,"");
                    }
                }


            }
        });

        dataList = getIntent().getStringArrayListExtra("dataList");
        RfList = getIntent().getStringArrayListExtra("RfList");
        orderno = getIntent().getStringExtra("orderno");
        id = getIntent().getStringExtra("id");
        offic_id = getIntent().getStringExtra("offic_id");

        if (dataList != null) {
            orderNum.setText(String.valueOf(dataList.size()));
        }
        realNum.setText(String.valueOf(RfList.size()));



        for (int i = 0; i < RfList.size(); i++) {
            rfid = rfid + RfList.get(i)+ ",";
        }
        if (!TextUtils.isEmpty(rfid))
            rfid = rfid.substring(0, rfid.length() - 1);
        else
            rfid = "-1";
        InitRecyclerView();
        //getOrderWashDetail();


        if (TextUtils.isEmpty(id)) {
            getDataDetails(rfid);
        }else {
            getData();
        }

    }

    private void InitRecyclerView() {
        mDistributeAdapter = new DistributeAdapter();
        mDistributeAdapter.addHeaderView( LayoutInflater.from(DistributeResultActivity.this).inflate(R.layout.item_distribute_result_details, null, false));
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(mDistributeAdapter);

    }


    private void getData(){

        StockProto.get().divide_rfids(rfid,orderno)
            .subscribeOn(Schedulers.io())
            .compose(this.<OrderRfidsBean>bindUntilEvent(ActivityEvent.DESTROY))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<OrderRfidsBean>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(OrderRfidsBean orderCheckBean) {
                    doStockData(orderCheckBean);
                }
            });
    }

    private void doStockData(OrderRfidsBean bean){
        mStockCheckList.clear();
        exisNumber = 0;
        NoEnvironment = 0;
        if (bean.data!= null&&bean.data.size()>0) {
            for (int i = 0;i < bean.data.size();i++){
                StockCheckData data = new StockCheckData(bean.data.get(i).title,bean.data.get(i).order_nums,bean.data.get(i).read_nums,
                    bean.data.get(i).hotel,bean.data.get(i).office);
                exisNumber = exisNumber + Integer.parseInt(bean.data.get(i).order_nums);
                if (TextUtils.isEmpty(bean.data.get(i).read_nums)){
                    NoEnvironment = NoEnvironment + 0;
                }else {
                    NoEnvironment = NoEnvironment + Integer.parseInt(bean.data.get(i).read_nums);
                }
                mStockCheckList.add(data);
            }
        }

        mDistributeAdapter.setNewData(mStockCheckList);
    }


    private void getDataDetails(String data){

        StockProto.get().rfid_spec(data)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<RFIDSpecListBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        showOneToast(e.getMessage());
                    }

                    @Override
                    public void onNext(RFIDSpecListBean dataBean) {
                        //mLaundryAdapter.setNewData(dataBean.data);
                        doStockData(dataBean);
                    }
                });
    }

    private void doStockData(RFIDSpecListBean bean){
        mStockCheckList.clear();
        exisNumber = 0;
        if (bean.data!= null&&bean.data.size()>0) {
            for (int i = 0;i < bean.data.size();i++){
                StockCheckData data;
                if (TextUtils.isEmpty(bean.data.get(i).user)) {
                    data  =
                            new StockCheckData(bean.data.get(i).title,"0", bean.data.get(i).count, bean.data.get(i).hotel,
                                    bean.data.get(i).office);
                }else {
                    data  =
                            new StockCheckData(bean.data.get(i).title,"0", bean.data.get(i).count, bean.data.get(i).hotel,
                                    bean.data.get(i).office+"_"+bean.data.get(i).user);
                }
                exisNumber = exisNumber + Integer.parseInt(bean.data.get(i).count);
                mStockCheckList.add(data);
            }
        }

        mDistributeAdapter.setNewData(mStockCheckList);
    }



    private void rfid_divide_new(final String rfid, final String wash_id, String confirm) {

//        if (TextUtils.isEmpty(wash_id)){
//            showOneToast("回收单号不能为空");
//            return;
//        }
        btn_sure.setClickable(false);
        btn_sure.setBackgroundResource(R.drawable.button_shape2);
        showWaitingDialog("请等待", false);
        StockProto.get().rfid_divide_new(rfid, offic_id, wash_id, confirm, new HttpProtocol.Callback<BackBean>() {
            @Override
            public void onSuccess(BackBean backBean) {
                dismissWaitingDialog();
                showOneToast(backBean.msg);
                LogPlus.e(backBean.data.order_id + "");
                getDetailData(backBean.data.order_id + "");
            }

            @Override
            public void onFailed(int code, ErrorMsgException e) {
                showOneToast(e.getMessage());
                dismissWaitingDialog();
                if (code == -101) {
                    SureDialog sureDialog =
                            new SureDialog(DistributeResultActivity.this, "提示有其他科室布草，是否确定生成送洗单，选“确定”，可以生成送洗单。");
                    sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            rfid_divide_new(rfid, wash_id, "1");
                        }

                        @Override
                        public void cancle() {
                            finish();
                        }
                    });
                }
            }
        });
    }




    private void getDetailData(String id) {
        StockProto.get()
                .getOrderDetail("rfid_divide_detail", id,
                        new HttpProtocol.Callback<OrderDetailBean>() {
                            @Override
                            public void onSuccess(OrderDetailBean orderDetailBean) {
                                dismissLoadingDialog();
                                Toast.makeText(getActivity(), orderDetailBean.msg, Toast.LENGTH_SHORT)
                                        .show();
                                Intent intent = new Intent(getActivity(), OrderDetailActivity1.class);
                                Bundle bundle = new Bundle();
                                bundle.putSerializable("detailData", orderDetailBean);
                                intent.putExtras(bundle);
                                intent.putExtra("type", 2);
                                startActivity(intent);
                                finish();
                            }

                            @Override
                            public void onFailed(int code, ErrorMsgException e) {
                                showOneToast(e.getMessage());
                                dismissLoadingDialog();
                                finish();
                            }
                        });
    }
}
